﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Ue.Framework.Collections;
using Ue.Infrastructure;
using Ue.Infrastructure.RepositoryFramework;
using Ue.Framework.Web;
using Ue.Infrastructure.Web.AsyncHandlers;
using Ue.Qcdz.Domain;
using Ue.Qcdz.Domain.Membership;
using Ue.Qcdz.Domain.Roles;

namespace Ue.Qcdz.UI.Controller
{
    public class UserController : AsyncResult
    {
        private User user;
        private string UserName;
        private string UserpassWord;
        private object isLoaded = new object();
        private IUserRepository userRepository;
        public UserController(AsyncCallback callback, HttpContext context, object state)
            : base(callback, context, state)
        {
            this.userRepository = RepositoryFactory.GetRepository<IUserRepository, User>();
            this.user = userRepository[context.Request.GetQueryValue<Guid>("UserId")];

        }
        public string ChangeStatus()
        {
            this.user.ChangeStatus();
            this.userRepository[this.user.Key] = this.user;
            return user.State.ToString();
        }

        private Role GetRole(string id)
        {
            //Guid roleId = new Guid(id"D58B0844-FB50-41AA-9CE2-38C50892E5D0");
            Guid roleId = new Guid(id);
            IRoleRepository repository =
            Ue.Infrastructure.RepositoryFramework.RepositoryFactory.GetRepository<IRoleRepository, Role>();
            Role role = repository.FindBy(roleId);
            return role;
        }

        public int UserLogin()
        {
            UserName = HttpContext.Current.Request.GetQueryValue<string>("UserName");
            UserpassWord = Ue.Framework.Security.DEncryptUtils.MD5EnCode(HttpContext.Current.Request.GetQueryValue<string>("UserpassWord"));
            user = userRepository.FindBy(UserName);
            if (user == null)
                return 0;//不存在该用户
            else
            {
                if (user.CheckPwd(UserpassWord))
                {
                    if (user.State == EntityState.Enable)
                    {
                        user.CreateFormsAuthentication();
                        if ((user.Roles.Contains(GetRole("D58B0844-FB50-41AA-9CE2-38C50892E5D0"))) || user.Roles.Contains(GetRole("F2CD22CC-E217-4F50-87E7-97DBA9197CA8")))
                            return 2;//管理员
                        return 1; //登陆成功
                    }
                    else
                    {
                        return -2;//禁用
                    }
                }
                else
                    return -1;//密码错误
            }
        }
        public void LoginOut()
        {

            user = userRepository.FindBy(HttpContext.Current.User.Identity.Name);
            if (user != null)
                user.SignOut();
        }
    }
}
